package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("DetectService")
@Transactional

public class DetectServiceImpl extends CmiEmaService implements DetectService {
	public DetectServiceImpl() {
	}

	@Transactional
	public Detect saveDetect(Detect detect) {
		Set<Detectdetail> existingDetectdetailsForDetect = new HashSet<Detectdetail>();
		Set<Detectfeature> existingDetectfeaturesForDetect = new HashSet<Detectfeature>();

		Set<Detectdetail> selectedDetectdetailsForDetect = detect.getDetectdetailsForDetect();
		Set<Detectfeature> selectedDetectfeaturesForDetect = detect.getDetectfeaturesForDetect();

		if (detect.getId() == null) {
			Detectdepartment detectdepartment = detectdepartmentDAO
					.findDetectdepartmentById(detect.getDetectdepartment().getId());
			Foodbatch foodbatch = foodbatchDAO.findFoodbatchById(detect.getFoodbatch().getId());
			User detector = userDAO.findUserById(detect.getDetector().getId());
			Subject subject = subjectDAO.findSubjectById(detect.getSubject().getId());

			Detect existingDetect = detectDAO.findDetectByPhysicalPrimaryKey(subject.getId(), foodbatch.getId(),
					detect.getDate(), detector.getId(), detectdepartment.getId());

			detect.setDetectdepartment(detectdepartment);
			detect.setFoodbatch(foodbatch);
			detect.setDetector(detector);
			detect.setSubject(subject);

			if (isEquals(detect, existingDetect)) {
				return existingDetect;
			}

			detect = detectDAO.store(detect);
			detectDAO.flush();

			for (Detectdetail relatedDetectdetail : selectedDetectdetailsForDetect) {
				relatedDetectdetail.setDetect(detect);
				detectdetailDAO.store(relatedDetectdetail);
			}
			for (Detectfeature relatedDetectfeature : selectedDetectfeaturesForDetect) {
				relatedDetectfeature.setDetect(detect);
				detectfeatureDAO.store(relatedDetectfeature);
			}
		} else {
			Detect existingDetect = detectDAO.findDetectByPrimaryKey(detect.getId());

			existingDetectdetailsForDetect = existingDetect.getDetectdetailsForDetect();
			existingDetectfeaturesForDetect = existingDetect.getDetectfeaturesForDetect();

			Set<Detectdetail> prepareDeleteDetectdetailsForDetect = new HashSet<Detectdetail>();
			Set<Detectdetail> prepareAddDetectdetailsForDetect = new HashSet<Detectdetail>();

			prepareDeleteDetectdetailsForDetect.addAll(selectedDetectdetailsForDetect);
			prepareDeleteDetectdetailsForDetect.addAll(existingDetectdetailsForDetect);

			prepareAddDetectdetailsForDetect.addAll(selectedDetectdetailsForDetect);
			prepareAddDetectdetailsForDetect.addAll(existingDetectdetailsForDetect);

			prepareDeleteDetectdetailsForDetect.removeAll(selectedDetectdetailsForDetect);
			prepareAddDetectdetailsForDetect.removeAll(existingDetectdetailsForDetect);

			for (Detectdetail relatedDetectdetail : prepareAddDetectdetailsForDetect) {
				relatedDetectdetail.setDetect(detect);
				detectdetailDAO.store(relatedDetectdetail);
			}

			for (Detectdetail relatedDetectdetail : prepareDeleteDetectdetailsForDetect) {
				relatedDetectdetail.setDetect(null);
				detectdetailDAO.store(relatedDetectdetail);
			}
			Set<Detectfeature> prepareDeleteDetectfeaturesForDetect = new HashSet<Detectfeature>();
			Set<Detectfeature> prepareAddDetectfeaturesForDetect = new HashSet<Detectfeature>();

			prepareDeleteDetectfeaturesForDetect.addAll(selectedDetectfeaturesForDetect);
			prepareDeleteDetectfeaturesForDetect.addAll(existingDetectfeaturesForDetect);

			prepareAddDetectfeaturesForDetect.addAll(selectedDetectfeaturesForDetect);
			prepareAddDetectfeaturesForDetect.addAll(existingDetectfeaturesForDetect);

			prepareDeleteDetectfeaturesForDetect.removeAll(selectedDetectfeaturesForDetect);
			prepareAddDetectfeaturesForDetect.removeAll(existingDetectfeaturesForDetect);

			for (Detectfeature relatedDetectfeature : prepareAddDetectfeaturesForDetect) {
				relatedDetectfeature.setDetect(detect);
				detectfeatureDAO.store(relatedDetectfeature);
			}

			for (Detectfeature relatedDetectfeature : prepareDeleteDetectfeaturesForDetect) {
				relatedDetectfeature.setDetect(null);
				detectfeatureDAO.store(relatedDetectfeature);
			}
			detect = detectDAO.store(detect);
			detectDAO.flush();
		}

		detectdetailDAO.flush();
		detectfeatureDAO.flush();
		return detect;
	}

	public void deleteDetect(Detect detect) {
		detectDAO.remove(detect);
		detectDAO.flush();
	}

	@Transactional
	public void deleteDetects(Set<Integer> deleteDetectsId) {
		Query query = detectDAO.createNamedQuery("deleteDetectsById", -1, -1);
		query.setParameter(1, deleteDetectsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Detect> loadDetects() {
		return detectDAO.findAllDetects();

	}

	@Transactional
	public Set<Detect> loadReferenceDetects(Set<Detect> detects) {
		Iterator<Detect> detectsIterator = detects.iterator();
		Set<Detect> referencedDetects = new HashSet<>();
		while (detectsIterator.hasNext()) {
			Detect currentDetect = detectsIterator.next();

			if (!currentDetect.getDetectdetailsForDetect().isEmpty()) {
				referencedDetects.add(currentDetect);
				continue;
			}

			if (!currentDetect.getDetectfeaturesForDetect().isEmpty()) {
				referencedDetects.add(currentDetect);
				continue;
			}
		}
		return referencedDetects;
	}

	public Set<Detect> loadDetectsByIdSet(Set<Integer> detectIdSet) {

		Iterator<Integer> detectIdIterator = detectIdSet.iterator();
		Set<Detect> detectSet = new HashSet<>();
		while (detectIdIterator.hasNext()) {
			Integer id = detectIdIterator.next();
			Detect currentDetect = detectDAO.findDetectById(id);
			detectSet.add(currentDetect);
		}
		return detectSet;
	}

	@Transactional
	public List<Detect> findAllDetects(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Detect>(detectDAO.findAllDetects(startResult, maxRows));
	}

	@Transactional
	public Detect findDetectByPrimaryKey(Integer id) {
		return detectDAO.findDetectByPrimaryKey(id);
	}

	@Transactional
	public Integer countDetects() {
		return ((Long) detectDAO.createQuerySingleResult("select count(o) from Detect o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetects(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Detect.class);
		return ((Long) detectDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countDetectsByName(String queryName) {
		Query query = detectDAO.createNamedQuery("countDetectsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Detect.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadDetectObjectReferencedSet(Detect detect) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (detect.getDetectdepartment() != null) {

			Set<Integer> detectdepartmentIds = new HashSet<Integer>();
			detectdepartmentIds.add(detect.getDetectdepartment().getId());
			objectReferencedSetMap.put("detectdepartmentIds", detectdepartmentIds);
		}
		if (detect.getFoodbatch() != null) {

			Set<Integer> foodbatchIds = new HashSet<Integer>();
			foodbatchIds.add(detect.getFoodbatch().getId());
			objectReferencedSetMap.put("foodbatchIds", foodbatchIds);
		}
		if (detect.getDetector() != null) {

			Set<Integer> detectorIds = new HashSet<Integer>();
			detectorIds.add(detect.getDetector().getId());
			objectReferencedSetMap.put("detectorIds", detectorIds);
		}
		if (detect.getSubject() != null) {

			Set<Integer> subjectIds = new HashSet<Integer>();
			subjectIds.add(detect.getSubject().getId());
			objectReferencedSetMap.put("subjectIds", subjectIds);
		}

		Set<Integer> detectdetailsIds = new HashSet<Integer>();
		for (Detectdetail obj : detect.getDetectdetailsForDetect()) {

			detectdetailsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("detectdetailsIds", detectdetailsIds);
		Set<Integer> detectfeaturesIds = new HashSet<Integer>();
		for (Detectfeature obj : detect.getDetectfeaturesForDetect()) {

			detectfeaturesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("detectfeaturesIds", detectfeaturesIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadDetectClassReferencedSet(Detect detect) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("detectdepartments", detectdepartmentDAO.findAllDetectdepartments());
		classReferencedSetMap.put("foodbatchs", foodbatchDAO.findAllFoodbatchs());
		classReferencedSetMap.put("users", userDAO.findAllUsers());
		classReferencedSetMap.put("subjects", subjectDAO.findAllSubjects());
		classReferencedSetMap.put("detectdetails", detectdetailDAO.findAllDetectdetails());
		classReferencedSetMap.put("detectfeatures", detectfeatureDAO.findAllDetectfeatures());

		return classReferencedSetMap;
	}

	public boolean isEquals(Detect detect, Object obj) {
		if (obj == detect)
			return true;
		if (!(obj instanceof Detect))
			return false;
		Detect comparedDetect = (Detect) obj;
		if (!CheckPropertyEqual(detect.getSubject().getId(), comparedDetect.getSubject().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detect.getFoodbatch().getId(), comparedDetect.getFoodbatch().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detect.getDate(), comparedDetect.getDate())) {
			return false;
		}
		if (!CheckPropertyEqual(detect.getDetector().getId(), comparedDetect.getDetector().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detect.getDetectdepartment().getId(), comparedDetect.getDetectdepartment().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

